package utils

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"github.com/SermoDigital/jose/jws"
	"github.com/SermoDigital/jose/jwt"
	"lottery/conf"
	"math/big"
	"time"
)

var puk ecdsa.PublicKey
var prk ecdsa.PrivateKey

func init() {
	ESKeyX := new(big.Int)
	ESKeyY := new(big.Int)
	ESKeyD := new(big.Int)

	ESKeyX.SetString(conf.EcdsaKeyX, 16)
	ESKeyY.SetString(conf.EcdsaKeyY, 16)
	ESKeyD.SetString(conf.EcdsaKeyD, 16)
	puk = ecdsa.PublicKey{
		Curve: elliptic.P256(),
		X:     ESKeyX,
		Y:     ESKeyY,
	}

	prk = ecdsa.PrivateKey{
		PublicKey: puk,
		D:         ESKeyD,
	}

}

// 生成 token 令牌
func GetESToken(data map[string]interface{}) (token string, err error) {

	payload := jws.Claims{}
	for k, v := range data {
		payload.Set(k, v)
	}

	now := time.Now()
	payload.SetIssuer(conf.Issuer)
	payload.SetIssuedAt(now)
	payload.SetExpiration(now.Add(time.Duration(conf.Expire) * time.Minute))
	jwt := jws.NewJWT(payload, jws.GetSigningMethod(conf.Method))

	tokenBytes, err := jwt.Serialize(&prk)
	if err != nil {
		return "", err
	}

	token = string(tokenBytes)
	return token, nil
}

// 验证 token 令牌
func VerifyESToken(token string) (ret bool, claims jwt.Claims, err error) {

	jwt, err := jws.ParseJWT([]byte(token))

	if err != nil {
		return
	}

	err = jwt.Validate(&puk, jws.GetSigningMethod(conf.Method))
	if err != nil {
		return
	}
	return true, jwt.Claims(), nil
}
